﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;

namespace YLPublicService.EnumExtension
{
    public static class EnumExtension
    {
        /// <summary>
        /// 尝试获取EnumMemberAttribute 上的Value 属性，如果没有返回空字符串
        /// </summary>
        /// <param name="e"></param>
        /// <returns></returns>
        public static string TryGetEnumMemberValue(this Enum e)
        {
            string value = "";
            Type t = e.GetType();
            var field = t.GetField(e.ToString());

            if (field == null)
            {
                return value;
            }
            var atts = field.GetCustomAttributes(false);
            if (atts.Count() == 0)
            {
                return value;
            }
            var enumMemberAtt = from att in atts
                                where att is EnumMemberAttribute
                                select att;
            if (enumMemberAtt.Count() == 0)
            {
                return value;
            }
            return (enumMemberAtt.First() as EnumMemberAttribute).Value;
        }
        public static int GetIndex(this Enum status)
        {
            return Convert.ToInt32(status);
        }
        public static T ToEnum<T>(this int i)
        {
            return (T)Enum.ToObject(typeof(T), i);
        }
        public static bool TryEnumMemberValueToEnum<T>(this String str, out T outV)
        {
            Type t = typeof(T);
            var fields = t.GetFields();
            var field = fields.Where(f =>
                {
                    var atts = f.GetCustomAttributes(false);
                    var enumMemberAtt = from att in atts
                                        where att is EnumMemberAttribute
                                        select att;
                    if (enumMemberAtt.Count() == 0) return false;
                    var tempAtt = enumMemberAtt.First() as EnumMemberAttribute;
                    return tempAtt.Value == str;
                });
            if (field.Count() > 0)
            {
                outV = (T)Enum.Parse(typeof(T), field.First().Name);
                return true;
            }
            outV = default(T);
            return false;
        }
    }
}
